import React from 'react'
import { Input, error, info, success, Modal, FileUpload, Button, Link, TitleBar, Table } from '../../../ui-components'
import { connect } from 'react-redux'
import style from './style.docManage'
import util from '../../../util'
import mime from 'mime-types'

export default 
@connect(({ documents, upload }) => ({ documents, upload }))
class extends React.Component {

  state = {
    deleteDocument: false,
    uploadDocument: false,
    readyUploadedFile: {},
    description: '',
    documentName: ''
  }

  readyUploadedFile = {}
  curDocument = {}

  requestDeleteDocument(doc) {
    this.curDocument = doc
    util.dialog.call(this, 'deleteDocument')
  }

  requestUploadDocument() {
    this.setState({
      uploadDocument: true
    })
  }

  uploadDocument() {
    const { description, documentName } = this.state
    const v = this.readyUploadedFile
    if (util.isNull(documentName)) return error('请填写文档名称!');
    if (util.isNull(v)) return error('请选择文件!');
    // 请求创建文档
    info('正在上传，请勿进行其他操作', true);
    const documentType = mime.extension(v.type);
    this.props.createDocument({
      scenario: 1,
      documentName: (documentName || v.name) + '.' + documentType,
      documentSize: v.size,
      documentType,
      description,
      storageStatus: 1
    }, ({ presignedUrl, documentId }) => {
      this.props.fileUpload({
        file: v.file,
        url: presignedUrl,
        cb: () => {
          // 更新文档状态
          this.props.updateDocument(documentId, { storageStatus: 2 }, () => {
            success('上传成功!')
            // 重新刷新列表
            this.props.fetchDocuments()
          })
        }
      })
    })
    this.closeUploadDocument()
  }

  closeUploadDocument() {
    this.setState({
      documentName: '',
      description: '',
      readyUploadedFile: {},
      uploadDocument: false
    })
    this.readyUploadedFile = {}
  }

  // 下载文档
  downloadDocument(doc) {
    this.props.downloadDocument(doc.documentId, res => {
      location.href = res.data.presignedUrl
    })
  } 

  // 删除文档
  deleteDocument() {
    this.props.deleteDocument(this.curDocument, () => {
      success('删除文档成功!')
      this.props.fetchDocuments()
    })
    util.dialog.call(this, 'deleteDocument')
  }

  // 上传文档
  handleUploadDocument(v) {
    this.readyUploadedFile = v
    this.setState({
      readyUploadedFile: v
    })
  }

  componentDidMount() {
    this.props.fetchDocuments()
  }

  render() {
    const { list } = this.props.documents
    const config = {
      model: {
        documentName: '文档',
        documentType: '类型',
        documentSize: '大小',
        others: ''
      },
      config: {
        others: '.2',
        documentSize: '.4',
        documentType: '.4'
      },
      map: {
        documentSize: v => util.size(v),
        others: (_, doc) => {
          return (
            <span data-role="table-hover">
              <Link 
                color="red" 
                label="删除" 
                onClick={() => this.requestDeleteDocument(doc)}/>
            </span>
          )
        },
        documentName: (v, doc) => !doc.description? (
          <Link label={v} onClick={() => this.downloadDocument(doc)}/>
        ): (
          <div>
            <Link label={v} onClick={() => this.downloadDocument(doc)}/>
            <div className={style['document-description']}>{ doc.description }</div>
          </div>
        )
      }
    }
    return (
      <div>
        <TitleBar
          label="入职文档"
          actions={[{
            label: "上传文档",
            handler: ::this.requestUploadDocument
          }]}
        />
        <div>
          <Table
            {...config}
            data={list}
          />
        </div>
        <Modal
          active={this.state.uploadDocument}
          onRequestClose={::this.closeUploadDocument}
					actions={['cancel', ::this.uploadDocument ]}
          title="上传文档"
        >
          <div className={style['upload-body']}>
            <Input onChange={e => this.setState({ documentName: e.target.value })} label="文档名称"/>
            <Input onChange={e => this.setState({ description: e.target.value })} label="补充说明(选填)"/>
            <FileUpload 
              button="green"
              label="选择文件" 
              onChange={::this.handleUploadDocument}
            />
            <div 
              className={style['upload-file-info']}
            > 
              { 
                this.state.readyUploadedFile.name? `文件信息: ${ this.state.readyUploadedFile.name }`: '' 
              }
            </div>
          </div>
        </Modal>
        <Modal
          active={this.state.deleteDocument}
          onRequestClose={() => util.dialog.call(this, 'deleteDocument')}
					actions={['cancel', ::this.deleteDocument ]}
          title="删除文档"
        >
          <div>
					  <p>确定删除<b>`{ this.curDocument.documentName }`</b>文档吗?</p>
          </div>
        </Modal>
      </div>
    )
  }
}
